<template>
  <div style="position: relative">
    <div v-if="handleType == 'look'" class="mask"></div>
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
      :wrapper-col="wrapperCol"
      style="display: flex; flex-wrap: wrap"
    >
      <a-form-item style="width: 100%" ref="name" label="单位名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入单位名称" />
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="shortName"
        label="简称"
        name="shortName"
      >
        <a-input v-model:value="formState.shortName" placeholder="请输入简称" />
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-left: 15px"
        ref="code"
        label="医疗机构编码"
        name="code"
      >
        <a-input
          v-model:value="formState.code"
          placeholder="请输入医疗机构编码"
        />
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="code"
        label="医疗机构编号"
        name="num"
      >
        <a-input
          disabled
          v-model:value="formState.num"
          placeholder="系统自动生成"
        />
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-left: 15px"
        ref="creditCode"
        label="企业信用代码"
        name="creditCode"
      >
        <a-input
          v-model:value="formState.creditCode"
          placeholder="请输入企业信用代码"
        />
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="addressCode"
        label="省市区"
        name="addressCode"
      >
        <a-cascader
          v-model:value="formState.addressCode"
          :options="treeData"
          :loadData="loadData"
          change-on-select
          placeholder="请选择省市区"
        >
        </a-cascader>
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-left: 15px"
        ref="address"
        label="详细地址"
        name="address"
      >
        <a-input
          v-model:value="formState.address"
          placeholder="请输入详细地址"
        />
      </a-form-item>
      <a-form-item
        style="width: 30%"
        ref="longitude"
        label="坐标-经度"
        name="longitude"
        required
      >
        <a-input
          style="width: 80%"
          v-model:value="formState.longitude"
          placeholder="经度"
        />
        <!-- <div style="display: flex; align-items: center">
          
          <a-input
            style="width: 140px; margin-left: 15px"
            v-model:value="formState.latitude"
            placeholder="维度"
          />
          
        </div> -->
      </a-form-item>
      <a-form-item
        style="width: 30%"
        ref="latitude"
        label="坐标-维度"
        name="latitude"
        required
      >
        <a-input
          style="width: 80%"
          v-model:value="formState.latitude"
          placeholder="维度"
        />
      </a-form-item>
      <a-form-item style="width: 30%" label=" ">
        <a-button type="link" @click="handleInnerVisible">
          <template #icon>
            <EnvironmentTwoTone />
          </template>
          地图定位</a-button
        >
      </a-form-item>
      <a-form-item style="width:100%">
        <a-button type="primary" @click="handleSave">确定</a-button>
      </a-form-item>
    </a-form>

    <a-modal
      width="40%"
      v-model:visible="innerVisible"
      title="坐标位置"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleSaveBmap"
    >
      <BMap class="h390" ref="bmap"></BMap>
    </a-modal>
  </div>
</template>
<script>
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRaw,
  toRef,
  toRefs,
  watch,
} from "vue";
import { EnvironmentTwoTone } from "@ant-design/icons-vue";
import BMap from "@/components/BMap/index.vue";
import TreeSelect from "@/components/TreeSelect";
import * as areaApi from "@/api/area";
import * as hospitalApi from "@/api/hospital";
import { message } from "ant-design-vue";
import { getUserInfo } from "@/utils/auth";
import { hospitalBaseSave, hospitalBaseDetails } from "@/api/hospital.js";
let validatePhone = async (rule, value) => {
  // var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
  var reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
  if (value == "") {
    return Promise.reject("请输入手机号");
  } else if (!reg.test(value)) {
    return Promise.reject("请输入正确手机号");
  } else {
    return Promise.resolve();
  }
};
const validateCreditCode = (rule, value, callback) => {
  {
    if (!value) {
      callback(new Error("请输入企业信用代码"));
    } else if (value.length > 22) {
      callback(new Error("企业信用代码长度小于22位"));
    } else {
      callback();
    }
  }
};
const validateCode = (rule, value, callback) => {
  {
    if (!value) {
      callback(new Error("请输入医疗机构编码"));
    } else if (value.length > 22) {
      callback(new Error("医疗机构编码长度小于22位"));
    } else {
      callback();
    }
  }
};
const validateName = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入单位名称"));
  } else if (
    value &&
    !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
  ) {
    callback(new Error("单位名称不超过100个英文字符或50个汉字"));
  } else {
    callback();
  }
};
const validateShortName = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入简称"));
  } else if (
    value &&
    !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
  ) {
    callback(new Error("简称不超过50个英文字符或25个汉字"));
  } else {
    callback();
  }
};
const validateAddress = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入详细地址"));
  } else if (
    value &&
    !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
  ) {
    callback(new Error("详细地址不超过100个英文字符或者50个汉字"));
  } else {
    callback();
  }
};
// const validatelongitudelatitude =
const validateUserName = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入管理员"));
  } else if (
    value &&
    !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
  ) {
    callback(new Error("管理员名称不超过50个英文字符或25个汉字"));
  } else {
    callback();
  }
};
const rules = {
  name: [
    {
      required: true,
      validator: validateName,
      trigger: "blur",
    },
  ],
  shortName: [
    {
      required: true,
      validator: validateShortName,
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      validator: validateCode,
      trigger: "blur",
    },
  ],
  creditCode: [
    {
      required: true,
      validator: validateCreditCode,
      trigger: "blur",
    },
  ],
  addressCode: [
    {
      required: true,
      message: "请选择省市区",
    },
  ],
  address: [
    {
      required: true,
      validator: validateAddress,
      trigger: "blur",
    },
  ],
  longitude: [
    {
      required: true,
      message: "请输入经度",
    },
  ],
  latitude: [
    {
      required: true,
      message: "请输入维度",
    },
  ],
  
};
const Freezeoptions = [
  {
    label: "禁用",
    value: 1,
  },
  {
    label: "开启",
    value: 0,
  },
];
export default defineComponent({
 
  components: {
    TreeSelect,
    BMap,
    EnvironmentTwoTone,
  },
  setup(props, { emit }) {
    const handleType = toRef(props, "handleType");
    const formRef = ref();
    const formState = reactive({
      id: "",
      adminId:'',
      name: "", //单位名称
      shortName: "", //简称
      code: "", //医疗机构编码
      creditCode: "", //企业信用代码
      num: "", //医疗机构编号
      addressCode: [], //
      address: "", //详细地址
      longitude: "", //经度
      latitude: "", //维度
    });
    // 省市区
    const _shq = reactive({
      treeData: [
        {
          value: "zhejiang",
          label: "Zhejiang",
          isLeaf: false,
        },
        {
          value: "jiangsu",
          label: "Jiangsu",
          isLeaf: false,
        },
      ],
    });
    // 获取省
    const getS_ = async () => {
      const { data } = await areaApi.getProvinceList();
      _shq.treeData = data.map((item) => {
        return {
          label: item.name,
          value: item.code,
          isLeaf: false,
          type: "provice",
        };
      });
    };

    // 动态获取下一级
    const loadData = (selectedOptions) => {
      console.log(1222);
      console.log(selectedOptions);
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily

      setTimeout(async () => {
        targetOption.loading = false;
        let res = [];
        if (targetOption.type == "provice") {
          res = await areaApi.getCityList({
            provinceCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: false,
              type: "city",
            };
          });
        } else if (targetOption.type == "city") {
          res = await areaApi.getRegionList({
            cityCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: false,
              type: "region",
            };
          });
        } else if (targetOption.type == "region") {
          res = await areaApi.getTownList({
            regionCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: true,
              type: "town",
            };
          });
        }

        _shq.treeData = [..._shq.treeData];
      }, 1000);
    };

    // 地图
    const bmap = ref(null);
    const innerVisible = ref(false);
    // 打开地图
    const handleInnerVisible = () => {
      innerVisible.value = true;
    };
    //获取地图数据
    const handleSaveBmap = (row) => {
      formState.longitude = bmap.value.form.longitude;
      formState.latitude = bmap.value.form.latitude;
      formState.address = bmap.value.form.address;
      innerVisible.value = false;
    };
    // 保存数据
    const handleSave = () => {
      formRef.value.validate().then(() => {
        let params = {
          ...toRaw(formState),
          provinceCode: formState.addressCode[0], //省编码
          cityCode: formState.addressCode[1], //市编码
          regionCode: formState.addressCode[2], //区编码
          townCode: formState.addressCode[3], //镇编码
        };
        console.log(params);
        hospitalBaseSave(params).then((res) => {
          if (res && res.success) {
            message.success("操作成功");
            getInfo()
          } else {
          }
        });
      });
    };
   
    const getInfo = ()=>{
      let hospitalBaseId = getUserInfo()
        ? JSON.parse(getUserInfo()).hospitalBaseId
        : {};
      hospitalBaseDetails(hospitalBaseId).then((res)=>{
        console.log(res)
        formState.id = res.data.id;
      formState.adminId = res.data.adminId;
      formState.name = res.data.name;
      formState.code = res.data.code;
      formState.shortName = res.data.shortName;
      formState.creditCode = res.data.creditCode;
      formState.num = res.data.num;
      formState.addressCode = [
        res.data.provinceCode,
        res.data.cityCode,
        res.data.regionCode,
        res.data.townCode,
      ];
      formState.address = res.data.address;
      formState.latitude = res.data.latitude;
      formState.longitude = res.data.longitude;
      })
    }
    onMounted(async () => {
      await getS_();
      
      getInfo()

    });
    return {
      formRef,
      handleType,
      wrapperCol: {
        span: 0,
      },
      formState,
      Freezeoptions,
      rules,
      ...toRefs(_shq),
      getS_,
      loadData,

      handleInnerVisible,
      innerVisible,
      handleSaveBmap,
      bmap,

      handleSave,
    
    };
  },
});
</script>
<style lang="scss" scoped>
.mask {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100000;
  width: 100%;
  height: 100%;
}
</style>